package com.minshenglife.zanzan.web.weixin;

import java.io.File;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jfree.util.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.minshenglife.zanzan.entity.weixin.ArticleTodb;
import com.minshenglife.zanzan.entity.weixin.AutomaticReply;
import com.minshenglife.zanzan.entity.weixin.Keyword;
import com.minshenglife.zanzan.entity.weixin.Material;
import com.minshenglife.zanzan.pub.utils.Message;
import com.minshenglife.zanzan.pub.utils.StringUtils;
import com.minshenglife.zanzan.service.ArticleService;
import com.minshenglife.zanzan.service.AutomaticReplyService;
import com.minshenglife.zanzan.service.KeywordService;
import com.minshenglife.zanzan.service.MaterialService;
import com.minshenglife.zanzan.web.weixin.model.ArticleTodbModel;
import com.minshenglife.zanzan.web.weixin.model.KeywordModel;
import com.nationsky.pub.utils.GsonUtils;

/**
 * 关键词自动回复controller
 * @author jianghaibo
 *
 */
@Controller
@RequestMapping("/material")
public class EMOMaterialController {
	Logger log = LoggerFactory.getLogger(EMOMaterialController.class);
	@Resource
	AutomaticReplyService automaticReplyService;
	@Resource
	KeywordService keywordService;
	@Resource
	MaterialService materialService;
	@Resource
	ArticleService articleService;
	
	/**
	 * 获取素材列表
	 * @param material	素材(需要materialType和appid)
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="manage.mge",method=RequestMethod.GET)
    public String findAll(Material material,ModelMap map,HttpServletRequest request, HttpServletResponse response){
		try {
			log.debug("要查看的公众号的appid--》"+material.getAppid());
			List<Material> list = materialService.findAll(material);
			log.debug("图文列表为--》"+GsonUtils.toGson(list));
			map.put("list", list);
			map.put("appid", material.getAppid());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/jsp/manage/wxMaterialManage";
	}
	
	@RequestMapping(value="getall.mge",method=RequestMethod.GET)
	@ResponseBody
    public Message getAll(Material material,HttpServletRequest request, HttpServletResponse response){
		Message message=null;
		try {
			log.debug("要查看的公众号的appid--》"+material.getAppid());
			List<Material> list = materialService.findAll(material);
			log.debug("图文列表为--》"+ GsonUtils.toGson(list));
			message = new Message(Message.STATE_200,"成功");
			message.setData(list);
		} catch (Exception e) {
			e.printStackTrace();
			message = new Message(Message.STATE_one,"服务器异常");
		}
		return message;
	}
	
	@RequestMapping(value="add.mge",method=RequestMethod.POST)
	@ResponseBody
    public Message add(Material material,ArticleTodbModel articleModel,HttpServletRequest request, HttpServletResponse response){
		Message message=null;
		log.debug("素材类型为-->"+GsonUtils.toGson(material));
		log.debug("图文列表为-->"+GsonUtils.toGson(articleModel));
		try{
			material = materialService.add(material);
			log.debug("保存到素材为---->"+GsonUtils.toGson(material));
			if("news".equals(material.getMaterialType())){
				articleService.addList(articleModel.getArticles(),material);
			}
			message = new Message(Message.STATE_200,"保存成功");
		} catch (Exception e) {
			e.printStackTrace();
			message = new Message(Message.STATE_one,"服务器异常");
		}
		return message;
	}
	
	@RequestMapping(value="delete.mge",method=RequestMethod.DELETE)
	@ResponseBody
    public Message delete(Material material, HttpServletRequest request, HttpServletResponse response){
		Message message=null;
		try {
			log.debug("要删除的素材的id为--》"+material.getId());
			material = materialService.get(material.getId());
			if("news".equals(material.getMaterialType())){
				articleService.deleteByMaterialId(material.getId());
			}
			materialService.delete(material);
			message = new Message(Message.STATE_200,"删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			message = new Message(Message.STATE_one,"删除失败");
		}
		return message;
	}
	
	@RequestMapping(value="get.mge",method=RequestMethod.GET)
    public String get(Material material,ModelMap map,HttpServletRequest request, HttpServletResponse response){
		try {
			material = materialService.get(material.getId());
			if(material.getMaterialType().equals("news")){
				List<ArticleTodb> list = articleService.findByMaterialId(material.getId());
				material.setArticleList(list);
			}
			map.put("material", material);
			map.put("appid", material.getAppid());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/jsp/manage/wxMaterialUpdateNews";
	}
	
	@RequestMapping(value="update.mge",method=RequestMethod.POST)
	@ResponseBody
    public Message update(Material material,ArticleTodbModel articleModel,HttpServletRequest request, HttpServletResponse response){
		Message message=null;
		try {
			if("news".equals(material.getMaterialType())){
				articleService.deleteByMaterialId(material.getId());
				articleService.addList(articleModel.getArticles(), material);
			}
			
			message = new Message(Message.STATE_200,"保存成功");
		} catch (Exception e) {
			e.printStackTrace();
			message = new Message(Message.STATE_one,"服务器异常");
		}
		return message;
	}
	
	/**
	 * 上传图文图片
	 * @return
	 */
	@RequestMapping(value="uploadImage.mge",method=RequestMethod.POST)
	public void uploadArticleImage(@RequestParam("fileToUpload") CommonsMultipartFile fileToUpload ,HttpServletRequest request, HttpServletResponse response){
		log.info("开始上传文件"+fileToUpload);
		Message message = null;
		PrintWriter writer = null;
//		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
		MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());

		MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
        /**构建图片保存的目录**/    
        String logoPathDir = "/images/weixin/article";     
        /**得到图片保存目录的真实路径**/    
        String logoRealPathDir = request.getSession().getServletContext().getRealPath(logoPathDir);     
        log.debug("得到图片保存目录的真实路径-->"+logoRealPathDir);
        /**根据真实路径创建目录**/    
        File logoSaveFile = new File(logoRealPathDir);     
        if(!logoSaveFile.exists())     
            logoSaveFile.mkdirs();           
        /**页面控件的文件流**/    
        MultipartFile multipartFile = multipartRequest.getFile("fileToUpload");    
        log.debug("页面控件的文件流-->"+multipartFile);
        /**获取文件的后缀**/    
//        String suffix = multipartFile.getOriginalFilename().substring  
//                        (multipartFile.getOriginalFilename().lastIndexOf("."));  
        String suffix = fileToUpload.getOriginalFilename().substring  
                (fileToUpload.getOriginalFilename().lastIndexOf("."));
//        /**使用UUID生成文件名称**/    
        String logImageName = UUID.randomUUID().toString()+ suffix;//构建文件名称     
//        String logImageName = multipartFile.getOriginalFilename();  
        /**拼成完整的文件保存路径加文件**/    
        String fileName = logoRealPathDir + "/" + logImageName;     
        log.debug("拼成完整的文件保存路径加文件-->" + fileName);
        File file = new File(fileName);          
        
        try {
        	response.setContentType("text/html");
        	writer = response.getWriter();
        	fileToUpload.transferTo(file);
//            multipartFile.transferTo(file);
            message = new Message(Message.STATE_200,"上传成功");
            message.setData(logoPathDir +"/"+ logImageName);
        } catch (Exception e) {     
            e.printStackTrace();     
            message = new Message(Message.STATE_one,"上传失败");
        }     
        String msgJson = GsonUtils.toGson(message);
        log.debug("发送的数据-->>"+msgJson);
        writer.write(msgJson);
//		return message;
	}
	
	@RequestMapping(value="deleteImage.mge",method=RequestMethod.DELETE)
	@ResponseBody
	public Message deleteArticleImg(String imgUrl, HttpServletRequest request, HttpServletResponse response){
		boolean isDelete = false;
		Message message = null;
		 /**构建图片保存的目录**/    
        String logoPathDir = "/images/weixin/article";     
        /**得到图片保存目录的真实路径**/    
        String logoRealPathDir = request.getSession().getServletContext().getRealPath(logoPathDir); 
        String logImageName = imgUrl.substring(imgUrl.lastIndexOf("/")+1);
        /**拼成完整的文件保存路径加文件**/    
        String fileName = logoRealPathDir + "/" + logImageName;  
        log.debug("要删除的图片路径为--》》" + fileName);
        File file = new File(fileName);
        if(file.exists()){
        	isDelete = file.delete();
        	log.debug("要删除的图片存在");
        }
        if(isDelete){
        	message = new Message(Message.STATE_200,"删除成功");
        	log.debug("删除的图片成功");
        }else{
        	message = new Message(Message.STATE_one,"删除失败");
        	log.debug("删除的图片失败");
        }
		return message;
	}
	
	@RequestMapping(value="toAddNewsPage.mge",method=RequestMethod.GET)
	public String toAddPage(String appid,ModelMap map){
		map.put("appid", appid);
		return "/jsp/manage/wxMaterialAddNews";
	}
}
